<!-- Send Funds Form -->
<form class="form-horizontal" id="send-form" data-toggle="validator" role="form">
    <input class="hidden" name="type" value="single" id="send-type">
    <ul class="nav nav-tabs">
        <li id="send-button-simple" class="active"><a href="#send-simple" data-toggle="tab" ><i class="fa fa-user"></i> Simple Send</a></li>
        <li id="send-button-multiple"><a href="#send-multi" data-toggle="tab"><i class="fa fa-users"></i> Multi Send</a></li>
    </ul>
    <div class="tab-content clearfix">

        <!-- Simple Send -->
        <div class="tab-pane active panel panel-default">
            <div class="panel-body">
                <div class="form-group" id="source-address-field">
                    <!-- Source Address Field -->
                </div>
                <div class="form-group" id="destination-address-field">
                    <!-- Destination Address Field -->
                </div>
                <div class="form-group" id="token-name-select-field">
                    <!-- Token Name Field  -->
                </div>
                <div class="form-group" id="available-field">
                    <!-- Available  Field -->
                </div>
                <div class="form-group" id="amount-field">
                    <!-- Amount Field -->
                </div>
                <div class="form-group" id="send-list-field" style="display:none;">
                    <!-- Mult-Peer-Multi-Asset (MPMA) List -->
                </div>
                <div class="form-group" id="memo-field">
                    <!-- Memo Field -->
                </div>
                <div class="form-group" id="tx-fee-field">
                    <!-- Transaction Fee Field -->
                </div>
                <div id="transaction-status"></div>
                <div id="btn-submit" class="btn btn-success pull-right"><i class="fa fa-lg fa-fw fa-paper-plane"></i> Send Funds</div>
                <div id="btn-cancel" class="btn btn-danger pull-right margin-right-5"><i class="fa fa-lg fa-fw fa-ban"></i> Cancel</div>
            </div>
        </div>
    </div>

</form>


<script>
// Handle generating a transaction using current data and passing it to a callback function
function generateTransaction(callback=null, broadcast=false){
    var vals    = array2Object($('#send-form').serializeArray()),
        network = (FW.WALLET_NETWORK==2) ? 'testnet' : 'mainnet',
        amt_sat = getSatoshis(vals.amount),
        asset   = (vals.name!='') ? vals.name : 'A' + Math.floor(Math.random() * 9999999999999999999);
        fee_sat = getSatoshis(vals['fee-amount']),
        is_data = (vals['memo-type']=='data') ? true : false,
        command = (broadcast) ? 'cpSend' : 'createSend';
    // Single Sends
    if(vals.type=='single'){
        // Placeholder to easily reference destinations in updateTransactionSize()
        FW.SEND_DESTINATIONS = vals.destination;
        eval(command)(network, vals.source, vals.destination, vals.memo, is_data, vals.name, amt_sat, fee_sat, callback);
    }
    // MPMA Sends        
    if(vals.type=='multiple'){
        command = (broadcast) ? 'cpMultiSend' : 'createMultiSend';
        var sends        = String($('#send-list').val()).split("\n"),
            destinations = [],
            assets       = [],
            quantities   = [],
            memos        = [],
            memo_is_hex  = [],
            isHex        = /^[0-9a-fA-F]+$/;
        // Convert send lines into arrays to pass with API call
        sends.forEach(function(send){
            var info     = String(send).trim().split(','),
                address  = String(info[0]).trim(),
                asset    = (info[1]) ? String(info[1]).trim() : '',
                quantity = (info[2]) ? String(info[2]).trim() : '',
                memo     = (info[3]) ? String(info[3]).trim().replace(/^"|"$/g,'') : '';
            // Re-assemble any memos which have commas
            if(memo!='')
                memo = String(info.slice(3,info.length).join(',')).trim().replace(/^"|"$/g,'');
            if(quantity.indexOf('.')!=-1){
                quantity = parseInt(quantity.replace('.',''));
            } else {
                quantity = parseInt(quantity);
            }
            destinations.push(address);
            assets.push(asset);
            quantities.push(quantity);
            memos.push(memo);
            memo_is_hex.push(isHex.test(memo));
        });
        vals.destination = destinations;
        vals.asset       = assets;
        vals.quantity    = quantities;
        vals.memo        = memos;
        vals.memo_is_hex = memo_is_hex;
        // Placeholder to easily reference destinations in updateTransactionSize()
        FW.SEND_DESTINATIONS = vals.destination;
        if(command=='cpMultiSend')
            cpMultiSend(network, vals.source, vals.destination, vals.memo, vals.memo_is_hex, vals.asset, vals.quantity, fee_sat, callback);
        if(command=='createMultiSend')
            createMultiSend(network, vals.source, vals.destination, vals.memo, vals.memo_is_hex, vals.asset, vals.quantity, fee_sat, null, callback);
    }
}

$(document).ready(function(){

    // Load form field
    $('#source-address-field').load('html/fields/source-address.html');
    $('#destination-address-field').load('html/fields/destination-address.html');
    $('#token-name-select-field').load('html/fields/token-name-select.html');
    $('#available-field').load('html/fields/available.html');
    $('#amount-field').load('html/fields/amount.html');
    $('#memo-field').load('html/fields/memo.html');
    $('#tx-fee-field').load('html/fields/tx-fee.html');
    $('#send-list-field').load('html/fields/send-list.html');


    $('#send-button-simple').click(function(){
        $('#send-type').val('single').change();
        $('#send-list-field').hide();
        $('#destination-address-field').show();
        $('#token-name-select-field').show();
        $('#available-field').show();
        $('#amount-field').show();
        $('#memo-field').show();
    });

    $('#send-button-multiple').click(function(){
        $('#send-type').val('multiple').change();
        $('#send-list-field').show();
        $('#destination-address-field').hide();
        $('#token-name-select-field').hide();
        $('#available-field').hide();
        $('#amount-field').hide();
        $('#memo-field').hide();
    });
    // Delay initializing some fields to give things a chance to load
    setTimeout(function(){

        // Handle loading any data from FW.DIALOG_DATA
        var data = FW.DIALOG_DATA;
        if(data.destination)
            $('#destination-address').val(data.destination);
        if(data.token){
            $('#token-name-select').val(data.token);
            $('#token-name-select').change();
        }
        if(data.message)
            $('#memo').val(data.message);
        if(data.amount)
            $('#amount').val(data.amount);

        // Reset dialog data so we don't reuse data on form in the future
        FW.DIALOG_DATA = {};

        // Initialize any tooltips
        $('[data-toggle="tooltip"]').tooltip({ 
            html: true,
            placement: 'bottom'
        }); 

        // Remove any error indicators when user changes a field value
        $('#send-form input').change(function(e){
            $(this).closest('.form-group').removeClass('has-error has-danger');
        });

        // Handle updating the transaction fee based on actual tx size
        updateTransactionSize();

    },100);

    // Submit form when user 'Send Funds' button
    $('#btn-submit').click($.debounce(100,function(e){
        if(FW.IGNORE_SUBMIT)
            return;
        $('#send-form').submit()
    }));

    // Hide the send form if users clicks 'cancel' button
    $('#btn-cancel').click($.debounce(100,function(e){
        FW.SEND_DESTINATIONS = false;
        dialogClose('dialog-send');
    }));

    // Handle form validation and displaying any errors
    $('#send-form').validator().on('submit', function(e){
        // prevent normal form submission
        e.preventDefault(); 
        // Get object with form values
        var vals   = array2Object($(this).serializeArray()),
            type   = vals.type,
            errors = [];
        console.log('vals=',vals);
        // Remove error indicators from any fields 
        $('.form-group').removeClass('has-error has-danger');

        // VALIDATION - Single Send
        if(type=='single'){
            // Verify we have a valid address
            if(!isValidAddress(vals.destination)){
                errors.push('You must enter a valid destination address!');
                $('#destination-address').closest('.form-group').addClass('has-error has-danger');
            }
            // Verify we have a token name
            if(typeof vals.name==='undefined'){
                errors.push('You must select a token to send!');
                $('#token-name-select').closest('.form-group').addClass('has-error has-danger');
            }
            // Verify we have valid amount 
            if(numeral(vals.amount).value()==0){
                errors.push('You must enter an amount which is greater than 0!');
                $('#amount').closest('.form-group').addClass('has-error has-danger');
            }
            // Verify that the memo is below the max allowed characters
            if(vals['memo'] && vals['memo']!=''){
                var memotype = vals['memo-type'],
                    max      = (memotype=='data') ? 68 : 34;
                if(vals['memo'].length>max){
                    errors.push('Maximum memo length for a ' + memotype + ' memo is ' + max + ' characters!');
                    $('#memo').closest('.form-group').addClass('has-error has-danger');
                }
            }
        }
        // VALIDATION - Multi-Send (MPMA)
        if(type=='multiple'){
            // Require a send list
            if(vals['send-list']==''){
                errors.push('You must enter a list of addresses, assets, and quantities!');
                $('#send-list').closest('.form-group').addClass('has-error has-danger');
            }
        }
        // Verify we have valid fee amount 
        if(numeral(vals['fee-amount']).value()==0){
            errors.push('You must enter a fee which is greater than 0.00000000!');
            $('#fee-amount').closest('.form-group').addClass('has-error has-danger');
        }
        // Display any error message
        if(errors.length){
            dialogMessage('<i class="fa fa-lg fa-fw fa-exclamation-circle"></i> Error(s)', errors.join('<br/>') );
        } else {
            // Callback to run after broadcasting send
            var doneCb = function(tx){
                if(tx){
                    dialogClose('dialog-send');
                    dialogMessage('<i class="fa fa-lg fa-send"></i> Send Successful', '<center>Your send has been broadcast to the network and should complete shortly.' +
                                  '<br/><br/><a class="btn btn-success" href="' + FW.EXPLORER_API +'/tx/' + tx + '" target="_blank">View Transaction</a></center>');
                }
            }
            // Handle processing a single send
            if(type=='single'){
                // Confirm the action with the user
                var title = '<img src="' + FW.EXPLORER_API + '/icon/' + FW.ASSET_INFO.asset + '.png" class="fw-icon-20 margin-right-5"> Confirm ' + vals.name + ' Send?';
                    msg   = '<center>Send <b>' + vals.amount + ' ' + vals.name + '</b><br/>to <b>' + vals.destination + '</b></center>';
            }
            if(type=='multiple'){
                var title = 'Confirm Send?';
                    sends = String($('#send-list').val()).split("\n"),
                    msg   = getConfirmationMessage('<center>Are you sure you want to process the ' + sends.length + ' sends listed below?</b></center>', vals);
            }
            dialogConfirm(title, msg, false, true, function(){ generateTransaction(doneCb, true); });
        }
    });
});
</script>